<?php
namespace backend\components;
use backend\models\Log;
use yii\base\Behavior;
use Yii;

/**
 * User: Drery
 * Date: 2016/3/2
 * Time: 11:30
 */
class LogComponent extends Behavior
{
    public static function serviceLog($event)
    {
        $service = Yii::$app->requestedRoute;
        if (in_array($service,self::except())) {
            return;
        }
        $Log = new Log();
        $Log->method = Yii::$app->request->method;
        $Log->service = $service;
        $params = array_merge(Yii::$app->request->get(),Yii::$app->request->post());
        if (isset($params['_csrf']))
            unset($params['_csrf']);
        $Log->params = json_encode($params);
        $Log->admin_user_id = empty(Yii::$app->user->id) ? 0 : Yii::$app->user->id;
        $Log->status_code = Yii::$app->response->statusCode;
        $Log->ip = ip2long(Yii::$app->request->userIP);
        $Log->success = Yii::$app->session->has('success') ? 1 : 0;
        $Log->save();
    }

    public static function except()
    {
        return ['public/ip','public/captcha','i/favicon.png','public/notice','public/study-detail'];
    }
}